﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Exhort.Configuration
{
    /// <summary>
    /// 实体配置工厂类
    /// </summary>
    internal static class EntityConfigurationFactory
    {
        /// <summary>
        /// 同步对象
        /// </summary>
        private static readonly object sync = new object();

        /// <summary>
        /// 唯一实例
        /// </summary>
        private static IEnumerable<IEntityConfiguration> singleton;

        /// <summary>
        /// 实体配置
        /// </summary>
        private static IEnumerable<IEntityConfiguration> Configurations
        {
            get
            {
                if (singleton == null)
                {
                    lock (sync)
                    {
                        if (singleton == null)
                        {
                            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

                            List<Type> types = new List<Type>();

                            foreach (var assembly in assemblies)
                            {
                                try
                                {
                                    types.AddRange(assembly.GetTypes().Where(m => m.GetInterfaces().Contains(typeof(IEntityConfiguration)) && !m.IsAbstract));
                                }
                                catch { }
                            }

                            singleton = types.Select(m => Activator.CreateInstance(m) as IEntityConfiguration);
                        }
                    }
                }

                return singleton;
            }
        }

        /// <summary>
        /// 初始化实体模型生成器
        /// </summary>
        /// <param name="modelBuilder">实体模型生成器</param>
        internal static void ConfigurationsInit(ModelBuilder modelBuilder)
        {
            foreach (var configuration in Configurations)
            {
                configuration.AddTo(modelBuilder);
            }
        }
    }
}